import { Empty, Select, Spin, Table } from "antd";
import { DatePicker } from 'antd';
import * as echarts from "echarts";
import { useEffect, useState } from "react";
import lessModule from "./index.module.less"
import dayjs from 'dayjs';
import { $eventBus } from "../../../../../../common/utils";
import { $Http } from "../../../../../../network";
const { RangePicker } = DatePicker;


// 数据管理页面-历史曲线页面-左边面板—echartsLine1组件
interface dataManagementPageHistoricalCurvePageLeftPanelComponentEchartsLine1ComponentInterface {
    indexName: string
    sourceData: object
}
const DataManagementPage_HistoricalCurvePage_LeftPanelComponent_EchartsLine1Component: React.FC<dataManagementPageHistoricalCurvePageLeftPanelComponentEchartsLine1ComponentInterface> = (props) => {
    let echartsLine1: echarts.ECharts

    const init_echarts = () => {
        echartsLine1 = echarts.init(document.getElementById("echartsLine1") as HTMLElement)
        window.addEventListener("resize", () => {
            echartsLine1.resize();
        })
        draw_echarts()
    }
    const draw_echarts = () => {
        const option = {
            tooltip: {
                trigger: "axis",
                backgroundColor: "rgba(13, 89, 128, 0.9)",
                borderColor: "#17A1E6",
                axisPointer: {
                    lineStyle: {
                        type: "solid",
                        color: "#17A1E6",
                    },
                },
                formatter(params: Array<object>) {
                    return `
                            <div class="${lessModule["dataManagementPageHistoricalCurvePageLeftPanel-echartsLine__tooltip"]}">
                                <span>${params[0]["axisValueLabel"]}</span>
                                <div class="${lessModule["echartsLine-tooltip__row"]}">
                                    <div class="${lessModule["tooltip-row__legend"]} ${lessModule["tooltip-row__legendLine"]}"></div>
                                    <div>${params[0]["data"]}</div>
                                </div>
                            </div>`;
                },
            },
            grid: {
                top: 40,
                left: 60,
                right: 20,
                bottom: 20,
            },
            xAxis: {
                type: "category",
                data: props.sourceData?.["time"],
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: "rgba(23, 161, 230, 0.5)",
                    },
                },

                axisLabel: {
                    align: "left",
                    color: "#7A8F99",
                    showMinLabel: true,
                    showMaxLabel: true,
                    formatter: (() => {
                        return (item: object, idx: number) => {
                            const isLast = idx === props.sourceData?.["time"]?.length - 1;
                            const label = isLast ? `{last|${item}}` : item;
                            return label;
                        };
                    })(),
                    interval: props.sourceData?.["time"]?.length / 4,
                    rich: {
                        last: {
                            width: 0,
                            align: "right",
                        },
                    },
                },
                splitLine: {
                    show: true,
                    lineStyle: {
                        color: "rgba(23, 161, 230, 0.3)",
                    },
                },
                axisTick: {
                    show: false,
                },
            },
            dataZoom: [
                {
                    type: "inside",
                    start: 0,
                    end: 20,
                },
                {
                    start: 0,
                    end: 20,
                },
            ],
            yAxis: {
                type: "value",
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: "rgba(23, 161, 230, 0.5)",
                    },
                },
                axisLabel: {
                    fontSize: 12,
                    color: "#7A8F99",
                },

                splitLine: {
                    lineStyle: {
                        color: "rgba(23, 161, 230, 0.3)",
                    },
                },
            },
            series: [
                {
                    data: props.sourceData?.["trend"],
                    type: "line",
                    color: "#2BEDE6",
                    symbol: "none",
                    smooth: true,
                    animation: false,
                },
            ],
        };

        echartsLine1.setOption(option);
    }

    useEffect(() => {
        init_echarts()
        return () => {
            echartsLine1?.dispose()
        }
    }, [props.sourceData])

    return (
        <div className={`${lessModule["homePageDataManagementPageHistoricalCurvePage-dataManagementPageHistoricalCurvePageLeftPanel__echartsLine"]}`} id="echartsLine1"> </div>
    )
}


// 数据管理页面-历史曲线页面-左边面板—echartsLine3组件
interface dataManagementPageHistoricalCurvePageLeftPanelComponentEchartsLine1ComponentInterface {
    indexName: string
    sourceData: object
}
const DataManagementPage_HistoricalCurvePage_LeftPanelComponent_EchartsLine3Component: React.FC<dataManagementPageHistoricalCurvePageLeftPanelComponentEchartsLine1ComponentInterface> = (props) => {
    let echartsLine1: echarts.ECharts

    const init_echarts = () => {
        echartsLine1 = echarts.init(document.getElementById("echartsLine3") as HTMLElement)
        window.addEventListener("resize", () => {
            echartsLine1.resize();
        })
        draw_echarts()
    }
    const draw_echarts = () => {
        const option = {
            tooltip: {
                trigger: "axis",
                backgroundColor: "rgba(13, 89, 128, 0.9)",
                borderColor: "#17A1E6",
                axisPointer: {
                    lineStyle: {
                        type: "solid",
                        color: "#17A1E6",
                    },
                },
                formatter(params: Array<object>) {
                    return `
                            <div class="${lessModule["powerSupplyQualityOfSubstationPageDrawerContentComponentChartsComponent-powerSupplyQualityOfSubstationPageDrawerContentComponentChartsComponentEchartsComponent__tooltip"]}">
                                <span>${params[0]["axisValueLabel"]}</span>
                                <div class="${lessModule["powerSupplyQualityOfSubstationPageDrawerContentComponentChartsComponentEchartsComponent-tooltip__row"]}">
                                    <div class="${lessModule["tooltip-row__legend"]} ${lessModule["tooltip-row__legendLine"]}"></div>
                                    <div>${params[0]["data"]}</div>
                                </div>
                            </div>`;
                },
            },
            grid: {
                top: 40,
                left: 60,
                right: 1,
                bottom: 20,
            },
            xAxis: {
                type: "category",
                data: props.sourceData?.["xList"],
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: "rgba(23, 161, 230, 0.5)",
                    },
                },

                axisLabel: {
                    align: "left",
                    color: "#7A8F99",
                    showMinLabel: true,
                    showMaxLabel: true,
                    formatter: (() => {
                        return (item: object, idx: number) => {
                            const isLast = idx === props.sourceData?.["xList"]?.length - 1;
                            const label = isLast ? `{last|${item}}` : item;
                            return label;
                        };
                    })(),
                    interval: props.sourceData?.["xList"]?.length / 4,
                    rich: {
                        last: {
                            width: 0,
                            align: "right",
                        },
                    },
                },
                splitLine: {
                    show: true,
                    lineStyle: {
                        color: "rgba(23, 161, 230, 0.3)",
                    },
                },
                axisTick: {
                    show: false,
                },
            },
            yAxis: {
                type: "value",
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: "rgba(23, 161, 230, 0.5)",
                    },
                },
                axisLabel: {
                    fontSize: 12,
                    color: "#7A8F99",
                },

                splitLine: {
                    lineStyle: {
                        color: "rgba(23, 161, 230, 0.3)",
                    },
                },
            },
            series: [
                {
                    data: [],
                    type: "line",
                    color: "#2BEDE6",
                    symbol: "none",
                    smooth: true,
                    animation: false,
                },
            ],
        };

        echartsLine1.setOption(option);
    }

    useEffect(() => {
        init_echarts()
        return () => {
            echartsLine1?.dispose()
        }
    }, [props.sourceData])

    return (
        <div className={`${lessModule["homePageDataManagementPageHistoricalCurvePage-dataManagementPageHistoricalCurvePageLeftPanel__echartsLine"]}`} id="echartsLine3"> </div>
    )
}

// 数据管理页面-历史曲线页面-左边面板
interface dataManagementPageHistoricalCurvePageLeftPanelComponentInterface {
    indexName: string
    sourceData: object
}
const DataManagementPage_HistoricalCurvePage_LeftPanelComponent: React.FC<dataManagementPageHistoricalCurvePageLeftPanelComponentInterface> = (props) => {
    console.log(props.sourceData);
    
    return (
        <div className={`${lessModule["homePageDataManagementPageHistoricalCurvePage-dataManagementPageHistoricalCurvePageLeftPanel"]}`}>
            <div className={`${lessModule["homePageDataManagementPageHistoricalCurvePage-dataManagementPageHistoricalCurvePageLeftPanel__title"]}`}>{props.indexName}曲线</div>
            {Object.keys(props.sourceData).length  ? <>
                {
                    ["电压偏差", "功率"].includes(props.indexName) ? <DataManagementPage_HistoricalCurvePage_LeftPanelComponent_EchartsLine3Component indexName={props.indexName} sourceData={props.sourceData} />
                        : <DataManagementPage_HistoricalCurvePage_LeftPanelComponent_EchartsLine1Component indexName={props.indexName} sourceData={props.sourceData} />
                }
            </> : <Spin size="large" />

            }
        </div>
    )
}



// 数据管理页面-历史曲线页面-右边面板-上方卡片
interface dataManagementPageHistoricalCurvePageRightPanelTopCardComponentInterface {
    get_indexName: Function
    get_sourceData: Function
}
const DataManagementPage_HistoricalCurvePage_RightPanelComponent_TopCardComponent: React.FC<dataManagementPageHistoricalCurvePageRightPanelTopCardComponentInterface> = (props) => {
    let [filterSourceList, setFilterSourceList] = useState<Array<object>>([])
    let [indexList, setIndexList] = useState<Array<object>>([])
    let [indexName, setIndexName] = useState<string>("")
    let [startDate, setStartDate] = useState<string>("")
    let [endDate, setEndDate] = useState<string>("")
    let [siteName, setSiteName] = useState<string>([...JSON.parse(sessionStorage.homePage_freewayList)[0].options, ...JSON.parse(sessionStorage.homePage_freewayList)[1].options][0]["label"])
    let [loopList, setLoopList] = useState<Array<object>>([])
    let [loopName, setLoopName] = useState<string>("")

    const http_getAllname = () => {
        $Http("getAllname", { substationName: siteName }).then((res) => {
            startDate = dayjs().subtract(1, "day").format("YYYY-MM-DD")
            endDate = dayjs().format("YYYY-MM-DD")
            loopList = []
            indexList = []
            filterSourceList = res["monitor_list"]

            filterSourceList?.forEach((item: object, idx: number) => {
                loopList[idx] = { label: item["cabinet"] }
            })
            filterSourceList?.[0]?.["index"]?.forEach((item: string, idx: number) => {
                indexList[idx] = { label: item }
            })
            loopName = loopList?.[0]?.["label"]
            indexName = indexList?.[0]?.["label"]
            setStartDate(startDate)
            setEndDate(endDate)
            setFilterSourceList([...filterSourceList])
            setLoopList([...loopList])
            setIndexList([...indexList])
            setLoopName(loopName)
            setIndexName(indexName)
        })
    }
    const change_indexName = (value: string) => {
        indexName = value
        setIndexName(indexName)
    }
    const change_date = (date: any, dateString: Array<string>) => {
        startDate = dateString[0]
        endDate = dateString[1]

        setStartDate(startDate)
        setEndDate(endDate)
    }
    const change_siteName = (value: string) => {
        siteName = value
        setSiteName(siteName)
        http_getAllname()

    }
    const change_loopName = (value: string) => {
        loopName = value
        indexList = []
        filterSourceList?.find((item) => item?.["cabinet"] === loopName)?.["index"]?.forEach((item: string, idx: number) => {
            indexList[idx] = { label: item }
        })
        indexName = indexList?.[0]?.["label"]
        setLoopName(loopName)
        setIndexList([...indexList])
        setIndexName(indexName)
    }

    const http_getHistoryData = () => {

        $Http("getHistoryData", {
            substation_name: siteName, monitor_name: loopName, index_name: indexName, start_time: startDate, end_time: endDate
        }).then((res) => {
            props.get_indexName(indexName)
            props.get_sourceData(res)
        })
    }
    const eventBus_on = () => {
        // 查询条件
        $eventBus.addListener("eventBus_tableSearchConditionData", () => {

            const interval = setInterval(() => {
                if (loopName && indexName) {
                    clearInterval(interval)
                    http_getHistoryData()
                }
            })



        })
    }
    const eventBus_off = () => {
        // 查询条件
        $eventBus.removeAllListeners("eventBus_tableSearchConditionData")
    }
    useEffect(() => {
        http_getAllname()
        return () => {
            eventBus_off()
        }
    }, [])

    useEffect(() => {
        eventBus_on()

    }, [indexName, startDate, endDate, siteName, loopName])
    return (
        <div className={`${lessModule["homePageDataManagementPageHistoricalCurvePage-dataManagementPageHistoricalCurvePageRightPanel__dataManagementPageHistoricalCurvePageRightPanelTopCard"]}`}>
            <div className={`${lessModule["dataManagementPageHistoricalCurvePageRightPanel-dataManagementPageHistoricalCurvePageRightPanelTopCard__row"]}`}>
                <span>指标：</span>
                <Select
                    value={indexName}
                    onChange={change_indexName}
                    options={indexList}
                    fieldNames={{ value: "label" }}
                />
            </div>
            <div className={`${lessModule["dataManagementPageHistoricalCurvePageRightPanel-dataManagementPageHistoricalCurvePageRightPanelTopCard__row"]}`}>
                <span>时间：</span>
                <RangePicker allowClear={false} separator={<span className={`${lessModule["dataManagementPageHistoricalCurvePageRightPanelTopCard-row__rangePickerSeparator"]}`}>至</span>} value={[dayjs(startDate, "YYYY-MM-DD"), dayjs(endDate, "YYYY-MM-DD")]} onChange={change_date} />
            </div>
            <div className={`${lessModule["dataManagementPageHistoricalCurvePageRightPanel-dataManagementPageHistoricalCurvePageRightPanelTopCard__row"]}`}>
                <span>站点：</span>
                <Select
                    value={siteName}
                    onChange={change_siteName}
                    options={[...JSON.parse(sessionStorage.homePage_freewayList)[0].options, ...JSON.parse(sessionStorage.homePage_freewayList)[1].options]}
                    fieldNames={{ value: "label" }}
                />
            </div>
            <div className={`${lessModule["dataManagementPageHistoricalCurvePageRightPanel-dataManagementPageHistoricalCurvePageRightPanelTopCard__row"]}`}>
                <span>回路：</span>
                <Select
                    value={loopName}
                    onChange={change_loopName}
                    options={loopList}
                    fieldNames={{ value: "label" }}
                />
            </div>
        </div>
    )
}

// 数据管理页面-历史曲线页面-右边面板-下方卡片
interface dataManagementPageHistoricalCurvePageRightPanelBottomCardComponentInterface {
    indexName: string
    sourceData: object
}
const DataManagementPage_HistoricalCurvePage_RightPanelComponent_BottomCardComponent: React.FC<dataManagementPageHistoricalCurvePageRightPanelBottomCardComponentInterface> = (props) => {
    const columnList = [{ title: '统计类型', dataIndex: 'type', }, { title: '最小值', dataIndex: 'siteName', }, { title: '平均值', dataIndex: 'tiem', }, { title: '最大值', dataIndex: 'tiem', }, { title: '95%最大值', dataIndex: 'tiem', }]
    let [sourceList, setSourceList] = useState<Array<object>>([])
    const className_tableRow = (record: object, idx: number) => {
        return idx % 2 ? lessModule["dataManagementPageHistoricalCurvePageRightPanelBottomCard-main__tableRow"] : ""
    }
    useEffect(() => {
        if (["电压偏差", "功率"].includes(props.indexName)) {
            sourceList = [{ type: "A相" }, { type: "B相" }, { type: "C相" }]
        } else {
            sourceList = [{ type: "三相" }]
        }
        setSourceList([...sourceList])
    }, [props.indexName])
    return (
        <div className={`${lessModule["homePageDataManagementPageHistoricalCurvePage-dataManagementPageHistoricalCurvePageRightPanel__dataManagementPageHistoricalCurvePageRightPanelBottomCard"]}`}>
            <header className={`${lessModule["dataManagementPageHistoricalCurvePageRightPanel-dataManagementPageHistoricalCurvePageRightPanelBottomCard__header"]}`}>数据统计</header>
            <div className={`${lessModule["dataManagementPageHistoricalCurvePageRightPanel-dataManagementPageHistoricalCurvePageRightPanelBottomCard__main"]}`}>

                <Table rowKey={(record) => record["time"]}
                    columns={columnList}
                    dataSource={sourceList}
                    pagination={false}
                    rowClassName={className_tableRow}
                />
            </div>
        </div>
    )
}
// 数据管理页面-历史曲线页面-右边面板
interface dataManagementPageHistoricalCurvePageRightPanelInterface {
    get_indexName: Function
    get_sourceData: Function
}
const DataManagementPage_HistoricalCurvePage_RightPanelComponent: React.FC<dataManagementPageHistoricalCurvePageRightPanelInterface> = (props) => {
    const [indexName, setIndexName] = useState<string>("")
    const [sourceData, setSourceData] = useState<object>({})
    const get_indexName = (value: string) => {
        setIndexName(value)
        props.get_indexName(value)

    }
    const get_sourceData = (data: object) => {
        setSourceData(data)
        props.get_sourceData(data)
    }
    return (
        <div className={`${lessModule["homePageDataManagementPageHistoricalCurvePage-dataManagementPageHistoricalCurvePageRightPanel"]}`}>
            <DataManagementPage_HistoricalCurvePage_RightPanelComponent_TopCardComponent get_indexName={get_indexName} get_sourceData={get_sourceData} />
            <DataManagementPage_HistoricalCurvePage_RightPanelComponent_BottomCardComponent indexName={indexName} sourceData={sourceData} />
        </div>
    )
}
// 主页-数据管理页面-历史曲线页面
const HomePage_DataManagementPage_HistoricalCurvePage: React.FC = () => {
    const [indexName, setIndexName] = useState<string>("")
    const [sourceData, setSourceData] = useState<object>({})
    const get_indexName = (value: string) => {
        setIndexName(value)

    }
    const get_sourceData = (data: object) => {
        setSourceData(data)

    }
    return (
        <div className={`${lessModule["homePageDataManagementPageHistoricalCurvePage"]}`}>
            <DataManagementPage_HistoricalCurvePage_LeftPanelComponent indexName={indexName} sourceData={sourceData} />
            <DataManagementPage_HistoricalCurvePage_RightPanelComponent get_indexName={get_indexName} get_sourceData={get_sourceData} />
        </div>
    )
}

export default HomePage_DataManagementPage_HistoricalCurvePage